<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI聊天助手</title>
    <style>
        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
        }
        
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #f5f7fa 0%, #e4edf5 100%);
            color: #333;
            line-height: 1.6;
            min-height: 100vh;
            padding: 20px;
            display: flex;
            flex-direction: column;
            align-items: center;
        }
        
        .container {
            width: 100%;
            max-width: 800px;
            background-color: white;
            border-radius: 16px;
            box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
            overflow: hidden;
            display: flex;
            flex-direction: column;
            height: 90vh;
        }
        
        header {
            background: linear-gradient(90deg, #3a7bd5 0%, #00d2ff 100%);
            color: white;
            padding: 20px;
            text-align: center;
            position: relative;
        }
        
        h1 {
            font-size: 2rem;
            margin-bottom: 8px;
            font-weight: 600;
        }
        
        .status {
            font-size: 0.9rem;
            opacity: 0.9;
            margin-bottom: 5px;
        }
        
        .status.connected {
            color: #4caf50;
        }
        
        .status.disconnected {
            color: #ff6b6b;
        }
        
        .chat-box {
            flex: 1;
            padding: 20px;
            overflow-y: auto;
            background-color: #f9fbfd;
            display: flex;
            flex-direction: column;
            gap: 15px;
        }
        
        .message {
            max-width: 80%;
            padding: 12px 18px;
            border-radius: 18px;
            word-wrap: break-word;
            position: relative;
            animation: fadeIn 0.3s ease;
        }
        
        .user-message {
            align-self: flex-end;
            background: linear-gradient(135deg, #3498db 0%, #1e6bc3 100%);
            color: white;
            border-bottom-right-radius: 5px;
        }
        
        .ai-message {
            align-self: flex-start;
            background: linear-gradient(135deg, #f0f5fa 0%, #e0ecfd 100%);
            color: #333;
            border-bottom-left-radius: 5px;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
        }
        
        .typing-indicator {
            align-self: flex-start;
            background-color: #f0f5fa;
            padding: 12px 18px;
            border-radius: 18px;
            display: none;
            animation: fadeIn 0.3s ease;
        }
        
        .typing-dots {
            display: flex;
            align-items: center;
        }
        
        .dot {
            width: 8px;
            height: 8px;
            background-color: #888;
            border-radius: 50%;
            margin: 0 3px;
            animation: bounce 1.5s infinite;
        }
        
        .dot:nth-child(2) {
            animation-delay: 0.2s;
        }
        
        .dot:nth-child(3) {
            animation-delay: 0.4s;
        }
        
        .input-container {
            padding: 15px 20px;
            background-color: white;
            border-top: 1px solid #eef2f7;
            display: flex;
            gap: 10px;
            position: relative;
        }
        
        #user-input {
            flex: 1;
            padding: 12px 15px;
            border: 2px solid #e1e8f0;
            border-radius: 24px;
            font-size: 1rem;
            outline: none;
            transition: border-color 0.3s;
            background-color: #f8fafd;
        }
        
        #user-input:focus {
            border-color: #3498db;
            box-shadow: 0 0 0 2px rgba(52, 152, 219, 0.2);
        }
        
        #send-button {
            width: 48px;
            height: 48px;
            border-radius: 50%;
            border: none;
            background: linear-gradient(135deg, #3a7bd5 0%, #00d2ff 100%);
            color: white;
            font-size: 1.2rem;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.3s ease;
            box-shadow: 0 4px 10px rgba(58, 123, 213, 0.3);
        }
        
        #send-button:hover {
            transform: scale(1.05);
            box-shadow: 0 6px 15px rgba(58, 123, 213, 0.4);
        }
        
        #send-button:active {
            transform: scale(0.98);
        }
        
        .error-message {
            background-color: #ffebee;
            color: #c62828;
            padding: 12px 18px;
            border-radius: 8px;
            margin: 15px;
            font-size: 0.9rem;
            animation: fadeIn 0.3s ease;
            display: none;
        }
        
        .placeholder {
            text-align: center;
            color: #a0aec0;
            font-style: italic;
            padding: 50px 20px;
            display: none;
        }
        
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        @keyframes bounce {
            0%, 100% { transform: translateY(0); }
            50% { transform: translateY(-5px); }
        }
        
        @media (max-width: 600px) {
            .container {
                height: 95vh;
                border-radius: 12px;
            }
            
            h1 {
                font-size: 1.5rem;
            }
            
            .message {
                max-width: 90%;
                padding: 10px 15px;
            }
            
            .input-container {
                padding: 12px;
            }
            
            #send-button {
                width: 44px;
                height: 44px;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <header>
            <h1>AI聊天助手</h1>
            <div class="status" id="status">正在连接到服务器...</div>
        </header>
        
        <div class="error-message" id="error-message"></div>
        
        <div class="chat-box" id="chat-box">
            <div class="placeholder" id="placeholder">开始对话吧！在这里输入消息并发送，或尝试命令如：清空对话、查看历史、OCR图片识别</div>
        </div>
        
        <div class="typing-indicator" id="typing-indicator">
            <div class="typing-dots">
                <div class="dot"></div>
                <div class="dot"></div>
                <div class="dot"></div>
            </div>
        </div>
        
        <div class="input-container">
            <input type="text" id="user-input" placeholder="输入消息或命令..." autocomplete="off">
            <button id="send-button">➤</button>
        </div>
    </div>

    <script>
        // DOM元素
        const chatBox = document.getElementById('chat-box');
        const userInput = document.getElementById('user-input');
        const sendButton = document.getElementById('send-button');
        const typingIndicator = document.getElementById('typing-indicator');
        const errorMessage = document.getElementById('error-message');
        const placeholder = document.getElementById('placeholder');
        const statusIndicator = document.getElementById('status');
        
        // 显示/隐藏占位符
        function updatePlaceholder() {
            placeholder.style.display = chatBox.children.length <= 1 ? 'block' : 'none';
        }
        
        // 添加消息到聊天框
        function addMessage(content, isUser = false, isError = false) {
            const messageDiv = document.createElement('div');
            messageDiv.classList.add('message');
            
            if (isError) {
                // 显示错误消息
                errorMessage.textContent = content;
                errorMessage.style.display = 'block';
                // 3秒后隐藏
                setTimeout(() => {
                    errorMessage.style.display = 'none';
                }, 5000);
            } else {
                messageDiv.classList.add(isUser ? 'user-message' : 'ai-message');
                messageDiv.textContent = (isUser ? '您: ' : 'AI: ') + content;
                chatBox.appendChild(messageDiv);
                chatBox.scrollTop = chatBox.scrollHeight;
            }
            
            updatePlaceholder();
        }
        
        // 连接到后端服务
        async function checkConnection() {
            try {
                const response = await fetch('http://localhost:8000/', {
                    method: 'GET'
                });
                
                if (response.ok) {
                    statusIndicator.textContent = "已连接到AI服务器";
                    statusIndicator.classList.add('connected');
                    statusIndicator.classList.remove('disconnected');
                } else {
                    throw new Error(`服务状态异常: ${response.status}`);
                }
            } catch (error) {
                statusIndicator.textContent = "无法连接服务: " + error.message;
                statusIndicator.classList.add('disconnected');
                statusIndicator.classList.remove('connected');
            }
        }
        
        // 发送消息到后端
        async function sendMessage() {
            const message = userInput.value.trim();
            if (!message) return;
            
            // 显示用户消息
            addMessage(message, true);
            userInput.value = '';
            
            // 显示AI正在输入
            typingIndicator.style.display = 'flex';
            chatBox.appendChild(typingIndicator);
            chatBox.scrollTop = chatBox.scrollHeight;
            
            try {
                // 发送请求到后端
                const response = await fetch('http://localhost:8000/chat', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ user_input: message })
                });
                
                // 检查响应状态
                if (!response.ok) {
                    // 尝试解析错误详细信息
                    try {
                        const errorData = await response.json();
                        throw new Error(`服务错误: ${errorData.detail || response.statusText}`);
                    } catch {
                        throw new Error(`HTTP错误: ${response.status} ${response.statusText}`);
                    }
                }
                
                // 解析成功响应
                const data = await response.json();
                
                if (data.status === 'success') {
                    // 显示AI回复
                    addMessage(data.response);
                } else {
                    // 显示错误消息
                    addMessage(`请求失败: ${data.message || '未知错误'}`, false, true);
                }
            } catch (error) {
                // 显示网络错误
                addMessage(`网络请求失败: ${error.message}`, false, true);
                console.error('请求失败:', error);
            } finally {
                // 隐藏正在输入指示器
                typingIndicator.style.display = 'none';
                updatePlaceholder();
            }
        }
        
        // 事件监听器
        sendButton.addEventListener('click', sendMessage);
        
        userInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') sendMessage();
        });
        
        // 初始化连接检查
        checkConnection();
        
        // 初始化界面
        updatePlaceholder();
    </script>
</body>
</html>